<template>
    <div class="table">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-cascades"></i> 表格</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
       <!-- <div class="coupon_box"> -->
            <div class="container">
               <div class="handle-box">
                <el-button type="primary" icon="el-icon-plus" class="mr10" @click="add">添加</el-button>
                            <!-- <el-button type="primary" icon="delete" class="handle-del mr10" @click="delAll">批量删除</el-button>
                            <el-select v-model="select_cate" placeholder="筛选条件" class="handle-select mr10">
                                <el-option key="1" label="活动日期" value="date"></el-option>
                                <el-option key="2" label="活动名称" value="name"></el-option>
                                <el-option key="3" label="需求人数" value="need"></el-option>
                            </el-select>
                            <el-input v-model="select_word" placeholder="筛选关键词" class="handle-input mr10"></el-input>
                            <el-button type="primary" icon="search" @click="search">搜索</el-button> -->
                        </div>
                        <el-table :data="tableData" border class="table" ref="multipleTable" @selection-change="handleSelectionChange">
                         <!--  <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                          <el-table-column prop="theme_name" label="所属" align="center">
                         </el-table-column>
                        
                         <el-table-column prop="rule" label="规则条件" align="center" width="150" :formatter="fromRule" show-overflow-tooltip>
                         </el-table-column>
                       <!--   <el-table-column prop="rule_fate" label="规则变量" align="center" width="200">
                         </el-table-column> -->
                         <el-table-column prop="way" label="方案" align="center"  width="150" :formatter="fromWay" show-overflow-tooltip>
                            
                         </el-table-column>
                       <!--   <el-table-column prop="way_fate" label="方案变量" align="center">
                         </el-table-column> -->
                         <el-table-column prop="issue" label="发布" align="center">

                            <template slot-scope="scope">
                                <el-switch v-model="scope.row.issue" active-color="#13ce66" inactive-color="#ff4949" @change="rack(scope.$index, scope.row)" :disabled="scope.row.theme_id > 1 ? true:false"></el-switch>
                            </template>
                            
                         </el-table-column>
                          <el-table-column prop="valid_time" label="有效期" align="center" width="320" :formatter="fromUTime">
                         </el-table-column>

                         <el-table-column fixed='right' label="操作" align="center" width='200'>
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-edit" :disabled="scope.row.theme_id 
                                > 1 ? true:false" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                                <el-button type="text" icon="el-icon-delete" :disabled="scope.row.theme_id > 1 ? true:false" class="red" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                            </template>
                         </el-table-column>
                </el-table>
                <div class="pagination">
                    <el-pagination background @current-change="handleCurrentChange" layout="prev, pager, next" :total="total">
                    </el-pagination>
                </div>

             </div>

           <!-- <div class="right-box" style="flex:0 0 200px;"> -->
               <!--  <div class="drag-box">
                <div class="drag-box-item">
                    <div class="item-title">规则设置</div> -->
                   <!--  <draggable v-model="todo" @remove="removeHandle" :options="dragOptions">
                        <transition-group tag="div" id="todo" class="item-ul">
                            <div v-for="(item,index) in todo" class="drag-list" :key="index">
                                {{item.content}}
                            </div>
                        </transition-group>
                    </draggable> -->
                 <!--  <div class="item-title-box">
                    <el-form ref="form" :model="form1" label-width="70px">
                        <el-form-item label="规则条件">
                            <el-input type="textarea" v-model="ruleTitle" :autosize="{ minRows: 2, maxRows: 4}"></el-input>
                        </el-form-item>
        
                             <el-form-item label="规则参数">
                                   <div class="rule-fate-box">
                                        <div class="fate-box">
                                        <span>在</span>
                                        <span><el-input v-model="ruleFate"></el-input></span>
                                        <span>之后</span>
                                    </div>
                                    <div class="fate-box">
                                        <span>第</span>
                                        <span><el-input-number v-model="fateNum" controls-position="right":min="1" :max="10" style="width: 90px;"></el-input-number></span>
                                        <span>个</span>
                                    </div>
                               </div>
                            </el-form-item>
                            
                    </el-form>
                  </div>  
                </div>
                <div class="drag-box-item">
                    <div class="item-title">方案设置</div> -->
                    <!-- <draggable v-model="doing" @remove="removeHandle" :options="dragOptions">
                        <transition-group tag="div" id="doing" class="item-ul">
                            <div v-for="(item,index) in doing" class="drag-list" :key="index">
                                {{item.content}}
                            </div>
                        </transition-group>
                    </draggable> -->
                <!-- </div> -->
               <!--  <div class="drag-box-item">
                    <div class="item-title">done</div>
                    <draggable v-model="done" @remove="removeHandle" :options="dragOptions">
                        <transition-group tag="div" id="done" class="item-ul">
                            <div v-for="(item,index) in done" class="drag-list" :key="index">
                                {{item.content}}
                            </div>
                        </transition-group>
                    </draggable>
                </div> -->
            <!-- </div> -->
       <!-- </div> -->

           <!-- </div> -->
        <!-- 编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="30%" >
            <el-form ref="form" :model="form" label-width="100px">
<!--                  <el-form-item label="活动名称">
                    <el-input v-model="form.active_name"></el-input>
                </el-form-item> -->
                 <el-form-item label="所属">
                 <el-select v-model="form.theme_id" clearable placeholder="请选择">
                    <el-option v-for="item in asList" :key="item.theme_id" :label="item.theme_name" :value="item.theme_id" :disabled="item.theme_id == 2 ? true:false" ><!-- -->
                    </el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="有效日期">
                    <el-date-picker v-model="form.valid_time" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                    
                </el-form-item>

                <el-form-item label="规则">
                 <el-select v-model="form.rule_id" clearable placeholder="请选择" @change="changeRule">
                    <el-option v-for="item in ruleList" :key="item.rule_id" :label="item.rule_name" :value="item.rule_id" :disabled="form.theme_id != 2 && item.rule_id == 4 ? true:false">
                    </el-option>
                  </el-select>
                </el-form-item>
              <el-form-item label="规则参数">
                  <el-input-number v-model="form.rule_fate " :min="0" :precision=" form.rule_id  == 2 ? 2:0" :step="0.5" :disabled=" form.rule_id == 1 || form.rule_id == 3 ? true:false" @blur="showRule" @change="showRule" ></el-input-number>
                   <span class="skim">{{ruleShow}}</span>
              </el-form-item>
              <el-form-item label="方案">
                 <el-select v-model="form.way_id" clearable placeholder="请选择">
                    <el-option v-for="item in wayList" :key="item.way_id" :label="item.way_name" :value="item.way_id"  :disabled="item.way_id == wayList.length ? true:false">
                    </el-option>
                  </el-select>
              </el-form-item>
               <el-form-item label="方案参数" >
                  <el-input-number v-model="form.way_fate" :min="0" :precision="2" :step="0.5" @blur="showWay" @change="showWay"></el-input-number>
                   <span class="skim">{{wayShow}}</span>
              </el-form-item>
               <!-- <el-form-item label="及时发布">
                  <el-switch v-model="form.issue" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
              </el-form-item> -->
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveEdit">确 定</el-button>
        </span>
    </el-dialog>

    <!-- 删除提示框 -->
    <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
        <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="delVisible = false">取 消</el-button>
            <el-button type="primary" @click="deleteRow">确 定</el-button>
        </span>
    </el-dialog> 
</div>
</template>

<script>
    import draggable from 'vuedraggable'
    export default {

        inject : ['reload'],
        name: 'basetable',
        data() {
            return {
                pickerOptions2: {
                  shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                      const end = new Date();
                      const start = new Date();
                      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                      picker.$emit('pick', [start, end]);
                  }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
              }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
          }
      }]
  },
                // url: './static/vuetable.json',
                tableData: [
                // {
                //     active_id:1,
                //     active_name:'邀请减免',
                //     valid_time:['2018-11-01','2018-11-11'],
                //     // valid_time:'2018-11-01 至 2018-11-11',
                //     banner:'static/img/lu1.png',
                //     active_hits:'968',
                //     active_share:'457',
                //     seed:'1198',
                //     hall:'18682',
                //     need:'3',
                //     friend_snap:'8.6',
                //     self_snap:'6',
                // }
                ],
                cur_page: 1,
                multipleSelection: [],
                select_cate: '',
                select_word: '',
                del_list: [],
                is_search: false,
                editVisible: false,
                delVisible: false,
                form: {
                    theme_id:'',
                    valid_time:[],
                    rule_id:'',
                    rule_fate:'',
                    way_id:'',
                    way_fate:'',
                    issue:'',
                },
                idx: -1,
                admininfo:JSON.parse(localStorage.getItem('ms_username')),
                total:1,
                title:'',

                /**/
                asList:[],
                ruleList:[],
                wayList:[],
                /*右边*/
                /*规则*/
                ruleTitle:'',
                ruleFate:'',
                fateNum:1,
                /*门店发布*/
                hascount:[],
                ruleShow:'',
                wayShow:'',
            }
        },
        created() {
            this.getData();
        },
        components:{
            draggable
        },
        computed: {
            data() {
                return this.tableData.filter((d) => {
                    let is_del = false;
                    for (let i = 0; i < this.del_list.length; i++) {
                        if (d.valid_time === this.del_list[i].valid_time) {
                            is_del = true;
                            break;
                        }
                    }
                    if (!is_del) {
                        if(d.valid_time.indexOf(this.select_word) > -1 ) {
                            return d;
                        }
                    }
                })
            }
        },
        methods: {
            // 分页导航
            handleCurrentChange(val) {
                this.cur_page = val;
                this.getData();
            },
            // 获取 easy-mock 的模拟数据
            getData() {
                // 开发环境使用 easy-mock 数据，正式环境使用 json 文件
                // if (process.env.NODE_ENV === 'development') {
                //     this.url = '/ms/table/list';
                // };
                // this.$axios.get(this.url, {
                //     page: this.cur_page
                // }).then((res) => {
                //     this.tableData = res.data.list;
                // })
                // console.log(this.admininfo)

                /*表格数据*/
                this.$axios.get('admin/voucher', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                        page: this.cur_page
                    }
                }).then((res) => {
                    if(res.data.status == 0){
                            this.tableData = res.data.data.data;
                            this.total = res.data.data.total 
                        }else if(res.data.status == 3){
                           this.$router.push('login') 
                        }
                    // this.uid = res.data.data.uid
                    // var has
                    // for(var i=0;i<this.tableData.length;i++){
                      // if(res.data.data.data[i].issue == true){
                        // this.hascount.push(i);
                        // console.log(i)
                      // }
                    // }
                    // console.log(this.hascount.length);

                })

                /*所属数据*/
                this.$axios.get('admin/voucher/aslist', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],

                    }
                }).then((res) => {
                    this.asList = res.data.data;
                })
                
                /*规则数据*/
                 this.$axios.get('admin/voucher/rulelist', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],

                    }
                }).then((res) => {
                    this.ruleList = res.data.data;
                })

                /*方案数据*/
                 this.$axios.get('admin/voucher/waylist', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],

                    }
                }).then((res) => {
                    this.wayList = res.data.data;
                })


            },
            search() {
                this.is_search = true;
                this.$axios.get('admin/banner/search', {
                    params:{
                        aid: this.admininfo['admin_id'],
                        token: this.admininfo['token'],
                        page: this.cur_page,
                        type: this.select_cate,
                        keyword:this.select_word
                    }
                }).then((res) => {
                    // this.tableData = res.data.data.data;

                    //  this.total = res.data.data.total
                    //  this.uid = res.data.data.uid
                    if(res.data.status == 0){
                        this.tableData = res.data.data.data;
                        this.total = res.data.data.total;

                    }else{
                        this.$message(res.data.msg)
                    }
                })


            },
            formatter(row, column) {
                return row.address;
            },
            filterTag(value, row) {
                return row.tag === value;
            },
            add(){
                this.title = '添加'
                this.form = {
                    theme_id:1,
                    valid_time:[],
                    rule_id:'',
                    rule_fate:'',
                    way_id:'',
                    way_fate:'',
                    issue:'',
                }
                this.editVisible = true;
            },
            handleEdit(index,row) {
                this.title = '编辑'
                this.idx = index;
                const item = this.tableData[index];
                this.form = {
                    // active_id:item.active_id,
                    // active_name:item.active_name,
                    // valid_time: item.valid_time,
                    // banner:item.banner,
                    // need:item.need,
                    // friend_snap:item.friend_snap,
                    // self_snap:item.self_snap,
                    coupon_id:item.coupon_id,
                    theme_id:item.theme_id,
                    valid_time:item.valid_time,
                    rule_id:item.rule_id,
                    rule_fate:item.rule_fate,
                    way_id:item.way_id,
                    way_fate:item.way_fate,
                    issue:item.issue,
                }
                this.editVisible = true;

            },
            handleDelete(index, row) {
                this.idx = index;
                this.delVisible = true;
            },
            delAll() {
                const length = this.multipleSelection.length;
                let str = '';
                this.del_list = this.del_list.concat(this.multipleSelection);
                for (let i = 0; i < length; i++) {
                    str += this.multipleSelection[i].name + ' ';
                }
                this.$message.error('删除了' + str);
                this.multipleSelection = [];
            },
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            // 保存编辑
            saveEdit() {
                // console.log(this.form.valid_time)
                for (var i = 0; i < this.form.valid_time.length; i++) {
                    var d = new Date(this.form.valid_time[i])
                    this.form.valid_time[i] = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
                }
                if(this.form.rule_id == 1 || this.form.rule_id == 3){
                    this.form.rule_fate = ''
                }
                if(this.form.issue == true){
                    this.form.issue = 1
                }else{
                    this.form.issue = 0
                }

                if(this.title == '添加'){
                    // let date = new Date()
                  // this.tableData.push(this.form)
                  // this.total = this.tableData.length+1
                  // this.editVisible = false;
                    // this.form.valid_time = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()
                    
                    // this.$set(this.tableData, this.idx, this.form);
                    

                    //  this.$axios.post('admin/type/typeadd',{
                    //     aid: this.admininfo.admin_id,
                    //     token: this.admininfo.token,
                    //     data: this.form.type_name
                    // }).then((res) =>{
                    //     if(res.data.status == 0){
                    //         this.$message.success(`添加第 ${this.tableData.length} 行成功`);
                    //         this.reload()
                    //     }else{
                    //         this.$message(res.data.msg);
                    //     }
                    // }) 
    
                    this.$axios.post('admin/voucher/add',{
                        aid:this.admininfo.admin_id,
                        token:this.admininfo.token,
                        data:this.form
                    }).then((res) =>{
                        if(res.data.status == 0){
                            this.$message.success('添加成功')
                            this.reload()
                        }else{
                            this.$message(res.data.msg)
                        }
                    })
                    

                }else if(this.title == '编辑'){
                    // this.$set(this.tableData, this.idx, this.form);
                    // this.editVisible = false;
                    // this.$message.success(`修改第 ${this.idx+1} 行成功`);

                    console.log(this.idx)
                    this.$axios.post('admin/voucher/up',{
                        aid: this.admininfo.admin_id,
                        token: this.admininfo.token,
                        // coupon_id:this.tableData[this.idx].coupon_id,
                        data: this.form
                    }).then((res) =>{
                        if(res.data.status == 0){
                            this.$message.success(`修改成功`);
                            this.reload()
                        }else{
                            this.$message.error(res.data.msg);
                        }
                    })


                }
            },
            // 确定删除
            deleteRow(){
                // console.log(this.tableData[this.idx].active_id)
                // this.tableData.splice(this.idx, 1);

                // this.delVisible = false;
                this.$axios.get('admin/voucher/del',{params:{
                    aid: this.admininfo.admin_id,
                    token: this.admininfo.token,
                    coupon_id:this.tableData[this.idx].coupon_id
                }}).then((res) =>{
                    if(res.data.status == 0){
                        this.$message.success(`删除成功`);
                        this.reload()
                    }else{
                        this.$message.error(res.data.msg);
                    }
                })
            },
            fromUTime(row, column){
              // const arr = row[column.property]
                /* 这里的 if(arr === undefined)
                 * 是根据自己的需求，决定arr长度为0时的判断条件
                 * 可以和这个不同
                 */ 
                // if(arr === undefined){
                //     return '0'
                // } else {
                //     return arr.length
                // }

                // var date =  new Date(obj);
                // var y = 1900+date.getYear();
                // var m = "0"+(date.getMonth()+1);
                // var d = "0"+date.getDate();
                // return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
                if(row.start && row.start){
                   return `${row.start} 至 ${row.end}`
                }
               return;

            },

            fromRule(row,column){
                if(row.r_fate == ''){
                    return row.rule_name;
                }
                var name = row.rule_name.trim()
                var index = new RegExp(row.r_fate)
                var str = name.replace(index,row.rule_fate);
                return str;

            },
            fromWay(row,column){
                var name = row.way_name.trim()
                var index = new RegExp(row.w_fate)
                var str = name.replace(index,row.way_fate);
                return str;
            },

            /*图片上传*/
            handleAvatarSuccess(res, file) {
                console.log(res);
                // this.imageUrl = URL.createObjectURL(file.raw);
                this.form.banner = res.data.data.src
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                  this.$message.error('上传头像图片只能是 JPG 格式!');
              }
              if (!isLt2M) {
                  this.$message.error('上传头像图片大小不能超过 2MB!');
              }
              return isJPG && isLt2M;
          },


          removeHandle(event){
            console.log(event);
            this.$message.success(`从 ${event.from.id} 移动到 ${event.to.id} `);
        },
        changeRule(){
          for(var i=0;i<this.ruleList.length;i++){
                    if(this.ruleList[i].rule_id == this.form.rule_id){
                       
                        this.ruleShow = this.ruleList[i].rule_name;
                    }
                }
              
        },
        showRule(){

             for(var i=0;i<this.ruleList.length;i++){
                    if(this.ruleList[i].rule_id == this.form.rule_id){
                        var index = new RegExp(this.ruleList[i].r_fate)
                        this.ruleShow = this.ruleList[i].rule_name.replace(index,this.form.rule_fate);
                    }
                }
                    
            },
        showWay(){

                for(var i=0;i<this.wayList.length;i++){
                    if(this.wayList[i].way_id == this.form.way_id){
                        var index = new RegExp(this.wayList[i].w_fate)
                        this.wayShow = this.wayList[i].way_name.replace(index,this.form.way_fate);
                    }
                }
                
            },
        rack(index, row) {
          var has = [];
          for(var i=0;i<this.tableData.length;i++){
            if(this.tableData[i].issue == true && this.tableData[i].theme_id == 1){
              has.push(i);
            }
          }
          console.log(has.length)
          if(has.length > 2){
            this.tableData[index].issue = false
             this.$message.error('只能发布两张门店优惠券')
          }else{
            this.$axios.post('admin/voucher/rack',{
                aid:this.admininfo.admin_id,
                token:this.admininfo.token,
                coupon_id:this.tableData[index].coupon_id
            }).then((res)=>{
                if(res.data.status == 0){
                    this.$message.success('修改成功');
                    
                }else{
                     this.$message.error(res.data.msg);
                     // row.issue = false
                }
                // this.reload()
            })
          }
           
        }

    }
}

</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.del-dialog-cnt{
    font-size: 16px;
    text-align: center
}
.table{
    width: 100%;
    font-size: 14px;
}
.red{
    color: #ff0000;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;

    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 320px;
    height: 178px;
}

.coupon_box{
    display: flex;
    justify-content:space-between;
}
.drag-box{
    /*flex:0 0 230px;*/
    flex: 1;
    display: flex;
    user-select: none;
    flex-direction: column;
    justify-content: center;
}
.drag-box-item {
    flex: 1;
    max-width: 330px;
    min-width: 90%;
    background-color: #fff;
    margin-left: 16px;
    border-radius: 6px;
    border: 1px #e1e4e8 solid;
    margin-bottom: 20px;
}
.item-title{
    padding: 8px 8px 8px 12px;
    font-size: 14px;
    line-height: 1.5;
    color: #24292e;
    font-weight: 600;
}
.item-ul{
    padding: 0 8px 8px;
    /*height: 500px;*/
    overflow-y: scroll;
}
.item-ul::-webkit-scrollbar{
    width: 0;
}
.drag-list {
    border: 1px #e1e4e8 solid;
    padding: 10px;
    margin: 5px 0 10px;
    list-style: none;
    background-color: #fff;
    border-radius: 6px;
    cursor: pointer;
    -webkit-transition: border .3s ease-in;
    transition: border .3s ease-in;
}
.drag-list:hover {
    border: 1px solid #20a0ff;
}
.drag-title {
    font-weight: 400;
    line-height: 25px;
    margin: 10px 0;
    font-size: 22px;
    color: #1f2f3d;
}
.ghost-style{
    display: block;
    color: transparent;
    border-style: dashed
}
.item-title-box{
    padding: 15px;
}
.rule-fate-box{
    display: flex;
    justify-content: space-between;
}
.fate-box{
    display: flex;
    width: 44%;
}
.fate-box span{
    
    white-space: nowrap;
}

.el-input__inner{
    width: 100% !important;
    max-width: 350px;
  }
  .skim{
    color: red;
    font-size: 12px;
  }
</style>
